import cloud from '@lafjs/cloud'
let data
let dbName = "admin-class"
const db = cloud.mongo.db

export default async function (ctx: FunctionContext) {
  data = ctx.body.data

  switch (ctx.body.type) {
    case "add":
      return await addClass()
      break;
    case "list":
      return await list()
      break;
    case "del":
      return await delFunc()
      break;
    case "details":
      return await details()
      break;
    case "update":
      return await update()
      break;
    case "graduation": //结业
      return await graduation()
      break;
    case "longest"://最长
      return await longestTeachingProgram()
      break;
    case "query":
      return await query()
      break;
    case "relatedArchives"://关联的档案
      return await relatedArchives()
      break;
    default:
      break;
  }
}

async function relatedArchives() {
  let aa = await db.collection("teaching-archives")
    .find({ bindClassIds: { $in: [data.classId] } })
    .toArray()
  return cloud.utils.requestReturn({ data: aa })
}

async function longestTeachingProgram() {
  const db = cloud.database();
  const fieldName = 'className'; // 替换为要查询的字段名称

  const result = await db.collection(dbName)
    .aggregate()
    .project({
      [fieldName]: 1,
      length: { $strLenCP: `$${fieldName}` } // 计算字段内容的长度
    })
    .sort({ length: -1 }) // 按长度降序排序
    .limit(1) // 只取最长的那一条
    .end();
  console.log("result", result)
  return cloud.utils.requestReturn({ data: result })
}

async function graduation() {
  let aa = await db.collection("admin-teaching-schedule").find({ classId: data._id }).toArray()
  for (let index = 0; index < aa.length; index++) {
    const element = aa[index];
    if (!element.hasOwnProperty("signInComplete")) {
      return cloud.utils.requestReturn({ code: 500, msg: "该班级未全部签到，请先签到完成后再结业" })
    }
  }
  let now = Date.now()
  await cloud.nw.db.update({
    dbName,
    whereJson: { _id: data._id },
    dataJson: { status: 2, graduationTime: now }  // 结业时间
  });
  //结业后，把结业时间给班级学员存上
  await cloud.nw.db.update({
    dbName: "admin-class-student",
    whereJson: { classId: data._id },
    dataJson: { graduationTime: now }  // 结业时间
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function query() {
  let aa = await db.collection(dbName).find({}).sort({ classState: 1 }).toArray()
  return cloud.utils.requestReturn({ data: aa })
}

async function update() {
  let query = { ...data }
  delete query._id
  await cloud.nw.db.update({
    dbName,
    whereJson: { _id: data._id },
    dataJson: query
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function addClass() {
  await cloud.nw.db.add({
    dbName,
    dataJson: data,
    cancelAddTime: false
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function details() {
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { _id: data._id },
  });
  return cloud.utils.requestReturn({ data: res })
}

async function delFunc() {
  await cloud.nw.db.del({
    dbName,
    whereJson: { _id: data._id }
  });
  // 删除该班级相关表的数据
  let dataSheet = ["admin-class-report-B7-Afterword",
    'admin-class-signIn',
    'admin-class-student',
    "admin-course-schedule", 'admin-teaching-schedule'
  ]
  for (let index = 0; index < dataSheet.length; index++) {
    const element = dataSheet[index];
    await cloud.nw.db.del({
      dbName: element,
      whereJson: { classId: data._id }
    });
  }
  return cloud.utils.requestReturn({ data: "" })
}



async function list() {
  let query = cloud.utils.fuzzyQuery(data)

  let res = await cloud.nw.db.selects({
    dbName,
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    whereJson: query,
    fieldJson: {
      "lessonEvaluationForm": 0,
      "assessmentRecord": 0
    },
    sortArr: [{ "name": "classState", "type": "asc" }, { "name": "classOpeningTime", "type": "desc" }, { "name": "_add_time", "type": "desc" }],
    // 副表列表
    foreignDB: [
      {
        dbName: "web-course",//副表 order
        localKey: "curriculumId",
        foreignKey: "_id",
        as: "course_Info",
        limit: 1,
        // 副表 where 条件
        whereJson: {},
        // 副表字段显示规则
        fieldJson: {
          "name": 1
        },
      },
      {
        dbName: "admin-users",//副表 order
        localKey: "classTeacherId",
        foreignKey: "_id",
        as: "classTeacher_Info",
        limit: 1,
        // 副表 where 条件
        whereJson: {},
        // 副表字段显示规则
        fieldJson: { "userName": 1 },
      },
      {
        dbName: "admin-teaching-schedule",//已上节数 
        localKey: "_id",
        foreignKey: "classId",
        as: "teaching_signInComplete",
        whereJson: { signInComplete: 1 },
        fieldJson: { date: 1, unitClassHours: 1 },
        limit: 100,
      },
      {
        dbName: "admin-teaching-schedule",//排期详情 
        localKey: "_id",
        foreignKey: "classId",
        as: "teaching_scheduling",
        fieldJson: { date: 1, unitClassHours: 1 },
        limit: 100,
      },
      {
        dbName: "admin-class-student",//排期详情 
        localKey: "_id",
        foreignKey: "classId",
        as: "class_students",
        fieldJson: { userId: 1 },
        limit: 1000,
      },
    ]
  });

  return cloud.utils.requestReturn({ data: res })
}
